package com.hl.im.gateway.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Properties;

/**
 * @author huanglin
 * @apiNote
 * @date: 2023/10/07 17:27
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class NacosConfig {
    private final GatewayConfig gatewayConfig;
    private ConfigService configService;

    @PostConstruct
    public ConfigService getConfigService() {
        try {
            Properties properties = new Properties();
            properties.setProperty("serverAddr", gatewayConfig.getNACOS_SERVER_ADDR());
            if (gatewayConfig.getNACOS_NAMESPACE() != null) {
                properties.setProperty("namespace", gatewayConfig.getNACOS_NAMESPACE());
            }
            return configService = NacosFactory.createConfigService(properties);
        } catch (Exception e) {
            log.error("初始化网关路由时发生错误", e);
            return null;
        }
    }

    public String getRouteConfig() {
        try {
            return configService.getConfig(gatewayConfig.getNACOS_ROUTE_DATA_ID(), gatewayConfig.getNACOS_ROUTE_GROUP(), gatewayConfig.getDEFAULT_TIMEOUT());
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }
}
